from django.shortcuts import render
from django.views import View
from django.http import JsonResponse, HttpResponse
from django_redis import get_redis_connection

from ihome_team7.libs.captcha.captcha import captcha
import json
import logging
import random
from ihome_team7.libs.yuntongxun.ccp_sms import CCP

logger = logging.getLogger('django')
# Create your views here.


class ImageCode(View):
    """图形验证码"""

    def get(self, request):
        """
        生成图形验证码
        :param request:  请求对象
        :return:  image/jpg
        """

        # 1.提取参数
        cur = request.GET.get('cur')

        text, image = captcha.generate_captcha()

        # 2.数据处理
        conn = get_redis_connection('verify_code')
        conn.setex('img_%s' % cur, 300, text)
        print(text)

        # 3.返回响应结果
        return HttpResponse(image, content_type='image/jpg')


class SMSCode(View):
    """短信验证码"""

    def post(self, request):
        """
        生成短信验证码
        :param request:  mobile id text
        :return:  Json
        """

        # 1.获取参数
        data = json.loads(request.body)
        mobile = data.get('mobile')
        cur = data.get('id')
        text = data.get('text')

        # 2.效验参数
        if not all([mobile, cur]):
            return JsonResponse({'errno': 4103, 'errmsg': '缺少必传参数'})

        # 提取redis中的图形验证码
        conn = get_redis_connection('verify_code')
        image_redis = conn.get('img_%s' % cur)
        if not image_redis:
            return JsonResponse({'errno': 4002, 'errmsg': '图形验证码过期'})

        # 避免恶意刷新图形验证码
        try:
            conn.delete('img_%s' % cur)
        except Exception as e:
            logger.error(e)

        # 对比图形验证码和输入
        if text.lower() != image_redis.decode().lower():
            return JsonResponse({'errno': 4103, 'errmsg': '图形验证码错误'})

        # 3.数据处理
        # 生成短信验证码
        phonecode = '%06d' % random.randint(0, 999999)
        print(phonecode)

        # 将短信验证码写入redis
        try:
            conn.setex('sms_%s' % mobile, 300, phonecode)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4001, 'errmsg': '写入数据库失败'})

        # 发送短信
        CCP().send_template_sms(mobile, [phonecode, 5], 1)

        # 4.返回响应对象
        return JsonResponse({"errno": "0", "errmsg": "发送成功"})
